package com.yequan.thread.cas;

import sun.misc.Unsafe;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : Administrator
 * @date : 2020/5/6
 */
public class Counter {

    private AtomicInteger acI = new AtomicInteger(0);
    private int i = 0;

    public static void main(String[] args) {
        Counter counter = new Counter();
        List<Thread> threads = new ArrayList<>(600);
        long start = System.currentTimeMillis();
        for (int j = 0; j < 100; j++) {
            Thread thread = new Thread(() -> {
                for (int i = 0; i < 10000; i++) {
                    counter.unsafeCount();
                    counter.safeCount();
                }
            });
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(counter.i);
            System.out.println(counter.acI);
            System.out.println(System.currentTimeMillis() - start);
        }
    }

    private void unsafeCount() {
        i++;
    }

    private void safeCount() {
        for (; ; ) {
            int i = acI.get();
            boolean success = acI.compareAndSet (i, ++i);
            if (success) {
                break;
            }
        }
    }

}
